package cloud.dandanit.itservice.service.impl;

import cloud.dandanit.itservice.entity.GiveLike;
import cloud.dandanit.itservice.entity.View;
import cloud.dandanit.itservice.mapper.ViewMapper;
import cloud.dandanit.itservice.service.ViewService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author luokai
 * @since 2022-07-03
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "ConstantConditions", "FieldCanBeLocal", "UnnecessaryLocalVariable"})
@Service
public class ViewServiceImpl extends ServiceImpl<ViewMapper, View> implements ViewService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private final String viewId = "1194556896025845888";

    /**
     * 获取浏览数
     * @return 浏览数
     */
    @Override
    public Integer getViewNum() {

        if (redisTemplate.opsForValue().get("viewNum") != null) {
            Integer viewNumRedis = Integer.valueOf(redisTemplate.opsForValue().get("viewNum"));
            return viewNumRedis;

        } else {

            View view = this.getOne(null);
            Integer viewNum = view.getViewNum();
            redisTemplate.opsForValue().set("viewNum", String.valueOf(viewNum));
            return viewNum;
        }
    }

    /**
     * 增加浏览数存redis)
     * @param viewNum 浏览数
     */
    @Override
    public void addViewNumToRedis(String viewNum) {

        redisTemplate.opsForValue().set("viewNum", viewNum,2, TimeUnit.MINUTES);
    }

    /**
     * 增加浏览数(从redis转存数据库)
     */
    @Override
    public void addViewNumFromRedisToMysql() {

        if (redisTemplate.opsForValue().get("viewNum")!=null) {

            Integer viewNum = Integer.valueOf(redisTemplate.opsForValue().get("viewNum"));

            View view = new View();
            view.setId(viewId);
            view.setViewNum(viewNum);

            this.updateById(view);

            //删除redis数据
            redisTemplate.delete("viewNum");
        }
    }
}
